const fs = require("fs");
const path = require("path");
const cheerio = require('cheerio');

const ICON_FONT_DIR = path.join(__dirname, "font_2711879_xczu27mvvig");//<===设置iconfont目录
const ICON_CLASS = "icon-svg";//设置class

const svgStr = /i='(.*)'/.exec(fs.readFileSync(path.join(ICON_FONT_DIR, "./iconfont.js"), "utf-8"))[1].trim();
const $ = cheerio.load(svgStr, { decodeEntities: false });
const genSVGXML = (conf) => `<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg class="iconfont_svg" height="200" width="${conf.width}" viewBox="${conf.viewBox}" version="1.1" xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink" >${conf.xml}</svg>`;
// const saveSVG = (className, xml) => fs.writeFileSync(path.join(ICON_FONT_DIR, "/svg/", className + ".svg"), xml);
const cssClassName = [], divDemo = [];
const css = `.${ICON_CLASS}{display:inline-block;background-size:100% 100%;background-repeat:no-repeat;background-position:center center;}` + $("symbol").toArray().map(vl => {
    let node = $(vl);
    let className = node.attr("id");
    // className = className.replace("icon-", ICON_CLASS + "-");//根据个人需要进行类名处理
    let viewBox = node.attr("viewBox");
    let viewBoxVal = viewBox.split(" ").map(Number);
    let xml = genSVGXML({
        viewBox,
        height: 200,
        width: viewBoxVal[2] / (viewBoxVal[3] / 200),
        xml: node.html()
    });
    // saveSVG(className, xml);//根据个人需要输出svg文件
    let datauri = 'data:image/svg+xml;base64,' + (Buffer.from(xml).toString('base64'));
    cssClassName.push(className);
    divDemo.push(`<div class="box"><div class="${ICON_CLASS} ${className}"></div><div>${className}</div></div>`);
    return `.${className}{background-image: url("${datauri}");}`;
}).join("");

let demoHtml = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
    <link rel="stylesheet" href="./iconsvg.css">
    <style>.box{min-height: 130px;width: 200px;margin: 20px 40px;float: left;text-align: center;}.icon-svg{width:60px;height:60px;}</style></head>
<body> ${divDemo.join("")}</body></html>`;

fs.writeFileSync(path.join(ICON_FONT_DIR, "iconsvg.css"), css);//输出css文件
fs.writeFileSync(path.join(ICON_FONT_DIR, "demo_svg.html"), demoHtml);//输出示例html
